<?php


namespace app\admin\controller;


use app\admin\model\GatherConfig;
use app\BaseController;
use app\Request;
use think\facade\View;

class QueryConfig extends BaseController
{
    //初始化
    public function initialize()
    {
        parent::initialize();
        $field_tag = self::CATPATHKEY;
        View::assign('field_tag', $field_tag);
    }

    //新增
    public function add(Request $request)
    {
        if ($request->isAjax()) {
            //$param = trim($request->param('name'));
            $param= preg_replace("/(\n)|(\s)|(\t)|(\')|(')|(，)/" ,',' ,trim($request->param('name')));
            $name_arr = explode(',',$param);
            $data = array_filter($name_arr); //去除空数组
            foreach ($data as $key=>$value){
                GatherConfig::create([
                    'name'=>$value,
                    'config_id'=>$key+1,
                    'field_tag' => $request->param('field_tag'),
                    'status'=>$request->param('status')
                ]);
            }
            return json(['code' => 200, 'url' => '', 'msg' => '添加成功！']);
        }
        return View::fetch('query/config/add');
    }

    /**
     * @param Request $request
     * @param string $ids
     * @return \response\Json
     * 删除
     */
    public function del(Request $request, $ids="")
    {
        if ($request->isAjax() && $ids) {
            $ids = explode(',', $ids);
            $count = GatherConfig::destroy(array_values($ids));
            if ($count) {
                return json(['code' => 200, 'url' => '', 'msg' => '删除成功！']);
            }
        }
    }

    /**
     * @param Request $request
     * @param $id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 编辑
     */
    public function edit(Request $request, $id){
        $model = GatherConfig::find($id);
        if ($request->isAjax()){
            $param = $request->param();
            $config = GatherConfig::update($param);
            if ($config){
                return json(['code' => 200, 'url' => '', 'msg' => '编辑成功！']);
            }
        }
        View::assign('model',$model);
        return View::fetch('query/config/edit');
    }
}